<template>
  <div class="supplier-management">
    <!-- 页面标题 -->
    <div class="flex justify-between items-center mb-6">
      <h1 class="text-2xl font-bold text-gray-800">供应商管理</h1>
      <el-button type="primary" @click="handleAdd" :icon="Plus">
        新增供应商
      </el-button>
    </div>

    <!-- 搜索表单 -->
    <el-card class="mb-6">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="供应商名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入供应商名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="供应商编码">
          <el-input
            v-model="searchForm.code"
            placeholder="请输入供应商编码"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="联系人">
          <el-input
            v-model="searchForm.contact"
            placeholder="请输入联系人"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-form-item>
        <el-form-item label="评价等级">
          <el-select v-model="searchForm.rating" placeholder="请选择评价等级" clearable style="width: 120px">
            <el-option label="A级" value="A" />
            <el-option label="B级" value="B" />
            <el-option label="C级" value="C" />
            <el-option label="D级" value="D" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :icon="Search">
            搜索
          </el-button>
          <el-button @click="handleReset" :icon="Refresh">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 供应商列表 -->
    <el-card>
      <el-table :data="supplierList" v-loading="loading" stripe>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="code" label="供应商编码" width="120" />
        <el-table-column prop="name" label="供应商名称" min-width="150" />
        <el-table-column prop="contact" label="联系人" width="100" />
        <el-table-column prop="phone" label="联系电话" width="130" />
        <el-table-column prop="email" label="邮箱" min-width="180" />
        <el-table-column prop="address" label="地址" min-width="200" show-overflow-tooltip />
        <el-table-column prop="rating" label="评价等级" width="100">
          <template #default="{ row }">
            <el-tag :type="getRatingType(row.rating)">{{ row.rating }}级</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
              {{ row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleQualification(row)" :icon="Document">
              资质
            </el-button>
            <el-button type="warning" size="small" @click="handleEdit(row)" :icon="Edit">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)" :icon="Delete">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="flex justify-center mt-6">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑供应商对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        class="supplier-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="供应商编码" prop="code">
              <el-input v-model="form.code" placeholder="请输入供应商编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入供应商名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系人" prop="contact">
              <el-input v-model="form.contact" placeholder="请输入联系人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="评价等级" prop="rating">
              <el-select v-model="form.rating" placeholder="请选择评价等级">
                <el-option label="A级" value="A" />
                <el-option label="B级" value="B" />
                <el-option label="C级" value="C" />
                <el-option label="D级" value="D" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio value="active">启用</el-radio>
            <el-radio value="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 资质管理对话框 -->
    <el-dialog
      v-model="qualificationDialogVisible"
      title="供应商资质管理"
      width="900px"
    >
      <div class="qualification-header mb-4">
        <el-button type="primary" @click="handleAddQualification" :icon="Plus">
          新增资质
        </el-button>
      </div>
      <el-table :data="qualificationList" stripe>
        <el-table-column prop="type" label="资质类型" width="150" />
        <el-table-column prop="name" label="资质名称" min-width="200" />
        <el-table-column prop="number" label="证书编号" width="180" />
        <el-table-column prop="issueDate" label="颁发日期" width="120" />
        <el-table-column prop="expireDate" label="到期日期" width="120">
          <template #default="{ row }">
            <span :class="{ 'text-red-500': isExpiringSoon(row.expireDate) }">
              {{ row.expireDate }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getQualificationStatusType(row.status)">
              {{ getQualificationStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleViewQualification(row)" :icon="View">
              查看
            </el-button>
            <el-button type="danger" size="small" @click="handleDeleteQualification(row)" :icon="Delete">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Search,
  Refresh,
  Edit,
  Delete,
  Document,
  View
} from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const qualificationDialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref()
const currentSupplier = ref(null)

// 搜索表单
const searchForm = reactive({
  name: '',
  code: '',
  contact: '',
  status: '',
  rating: ''
})

// 供应商表单
const form = reactive({
  id: null,
  code: '',
  name: '',
  contact: '',
  phone: '',
  email: '',
  address: '',
  rating: 'B',
  status: 'active',
  remark: ''
})

// 表单验证规则
const rules = {
  code: [
    { required: true, message: '请输入供应商编码', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入供应商名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  contact: [
    { required: true, message: '请输入联系人', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入地址', trigger: 'blur' }
  ],
  rating: [
    { required: true, message: '请选择评价等级', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 供应商列表
const supplierList = ref([])

// 资质列表
const qualificationList = ref([])

// 获取评价等级类型
const getRatingType = (rating: string) => {
  const types = {
    A: 'success',
    B: 'primary',
    C: 'warning',
    D: 'danger'
  }
  return types[rating] || 'info'
}

// 获取资质状态类型
const getQualificationStatusType = (status: string) => {
  const types = {
    valid: 'success',
    expiring: 'warning',
    expired: 'danger'
  }
  return types[status] || 'info'
}

// 获取资质状态标签
const getQualificationStatusLabel = (status: string) => {
  const labels = {
    valid: '有效',
    expiring: '即将到期',
    expired: '已过期'
  }
  return labels[status] || '未知'
}

// 检查资质是否即将到期
const isExpiringSoon = (expireDate: string) => {
  const expire = new Date(expireDate)
  const now = new Date()
  const diffTime = expire.getTime() - now.getTime()
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  return diffDays <= 30 && diffDays > 0
}

// 获取供应商列表
const getSupplierList = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    const mockData = [
      {
        id: 1,
        code: 'SUP001',
        name: '北京科技有限公司',
        contact: '张经理',
        phone: '13800138001',
        email: 'zhang@example.com',
        address: '北京市朝阳区科技园区',
        rating: 'A',
        status: 'active',
        createTime: '2024-01-15 10:30:00',
        remark: '优质供应商'
      },
      {
        id: 2,
        code: 'SUP002',
        name: '上海制造集团',
        contact: '李总监',
        phone: '13800138002',
        email: 'li@example.com',
        address: '上海市浦东新区工业园',
        rating: 'B',
        status: 'active',
        createTime: '2024-01-20 14:20:00',
        remark: '合作稳定'
      },
      {
        id: 3,
        code: 'SUP003',
        name: '广州贸易公司',
        contact: '王主管',
        phone: '13800138003',
        email: 'wang@example.com',
        address: '广州市天河区商务中心',
        rating: 'C',
        status: 'inactive',
        createTime: '2024-02-01 09:15:00',
        remark: '暂停合作'
      }
    ]
    
    supplierList.value = mockData
    pagination.total = mockData.length
  } catch (error) {
    ElMessage.error('获取供应商列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  getSupplierList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    code: '',
    contact: '',
    status: '',
    rating: ''
  })
  handleSearch()
}

// 新增供应商
const handleAdd = () => {
  dialogTitle.value = '新增供应商'
  Object.assign(form, {
    id: null,
    code: '',
    name: '',
    contact: '',
    phone: '',
    email: '',
    address: '',
    rating: 'B',
    status: 'active',
    remark: ''
  })
  dialogVisible.value = true
}

// 编辑供应商
const handleEdit = (row: any) => {
  dialogTitle.value = '编辑供应商'
  Object.assign(form, { ...row })
  dialogVisible.value = true
}

// 删除供应商
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除供应商 "${row.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    ElMessage.success('删除成功')
    getSupplierList()
  } catch (error) {
    // 用户取消删除
  }
}

// 资质管理
const handleQualification = (row: any) => {
  currentSupplier.value = row
  // 模拟获取资质数据
  qualificationList.value = [
    {
      id: 1,
      type: '营业执照',
      name: '企业法人营业执照',
      number: '91110000123456789X',
      issueDate: '2020-01-15',
      expireDate: '2030-01-15',
      status: 'valid'
    },
    {
      id: 2,
      type: 'ISO认证',
      name: 'ISO9001质量管理体系认证',
      number: 'ISO9001-2024-001',
      issueDate: '2024-01-01',
      expireDate: '2025-02-15',
      status: 'expiring'
    }
  ]
  qualificationDialogVisible.value = true
}

// 新增资质
const handleAddQualification = () => {
  ElMessage.info('新增资质功能开发中...')
}

// 查看资质
const handleViewQualification = (row: any) => {
  ElMessage.info('查看资质详情功能开发中...')
}

// 删除资质
const handleDeleteQualification = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除资质 "${row.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    ElMessage.success('删除成功')
    // 重新获取资质列表
  } catch (error) {
    // 用户取消删除
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success(form.id ? '更新成功' : '创建成功')
    dialogVisible.value = false
    getSupplierList()
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitLoading.value = false
  }
}

// 关闭对话框
const handleDialogClose = () => {
  formRef.value?.resetFields()
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  getSupplierList()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  getSupplierList()
}

// 组件挂载时获取数据
onMounted(() => {
  getSupplierList()
})
</script>

<style scoped>
.supplier-management {
  padding: 20px;
}

.search-form .el-form-item {
  margin-bottom: 0;
}

.supplier-form .el-select {
  width: 100%;
}

.qualification-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.text-red-500 {
  color: #ef4444;
}
</style>